package org.tote.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.tote.command.UserCommand;
import org.tote.service.user.UserService;

@Controller
public class AuthenticationController implements BaseController {

	//private static final String HOME_PAGE_VIEW = "/";
	private static final String USER_COMMAND_NAME = "userCommand";
	private static final String REGISTRATION_VIEW = "registration";
	private static final String REGISTERED_SUCCESSFULLY_VIEW = "registrationSuccessful";
	private static final String RESTORE_PASSWORD_VIEW = "restorePasswordForm";
	private static final String RESTORE_PASSWORD_RESULT_VIEW = "restorePasswordResult";
	private static final String ACTIVATION_ERROR = "activationError";
	private static final String ACTIVATION_SUCCESSFUL = "activationSuccessful";

	private static final String ERROR_MESSAGE = "errorMessage";
	private static final String RESTORE_PASSWORD_MESSAGE = "passwordRestoreResult";

	private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationController.class);

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(@RequestParam(value = "failure", required = false) Boolean failure,
			Map<String, Object> model) {
		return "login";
	}

	@RequestMapping(value = "/activate/{token}", method = RequestMethod.GET)
	public String activateUser(@PathVariable("token") String token, HttpServletRequest request) {
		if (userService.authorizeUserByToken(token, request))
			return ACTIVATION_SUCCESSFUL;
		else
			return ACTIVATION_ERROR;
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String loadRegistrationFrom(Map<String, Object> model) {
		model.put(USER_COMMAND_NAME, new UserCommand());

		return REGISTRATION_VIEW;
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String registerUser(@ModelAttribute @Valid UserCommand userCommand,
			BindingResult bindingResult, Map<String, Object> model) {
		if (bindingResult.hasErrors()) {
			return REGISTRATION_VIEW;
		}

		try {
			if (StringUtils.isEmpty(userCommand.getNewPassword())
					|| StringUtils.isEmpty(userCommand.getConfirmedPassword())
					|| !userCommand.getNewPassword().equals(userCommand.getConfirmedPassword()))
				throw new RuntimeException("Password empty or doesn't math");
			userCommand.setPassword(userCommand.getConfirmedPassword());
			userService.registerUser(userCommand.getAsUser());
			return REGISTERED_SUCCESSFULLY_VIEW;
		} catch (Throwable e) {//UserAlreadyExistException e) {
			LOGGER.error("Error registering user: " + userCommand, e);
			model.put(ERROR_MESSAGE, e.getMessage());
			return REGISTRATION_VIEW;
		}
	}

	@RequestMapping(value = "/restorePassword", method = RequestMethod.GET)
	public String loadRestorePasswordForm() {
		return RESTORE_PASSWORD_VIEW;
	}

	@RequestMapping(value = "/restorePassword", method = RequestMethod.POST)
	public String restorePassword(@RequestParam("userEmail") String userEmail,
			Map<String, Object> model) {
		try {
			userService.restorePassword(userEmail);
			model.put(RESTORE_PASSWORD_MESSAGE,
					"Your password successfully restored. Check you email box.");

			return RESTORE_PASSWORD_RESULT_VIEW;
		} catch (Throwable e) {
			model.put(ERROR_MESSAGE, "Your password not restored. Caused by: " + e.getMessage());
			return RESTORE_PASSWORD_VIEW;
		}

	}
}
